package com.cgycms.webloggather.file;

import com.cgycms.weblogcommon.model.WebLogMeta;
import com.cgycms.webloggather.netty.NettyClient;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName : FileListener
 * @Description : 文件目录监听器
 * @Author : cgy
 * @Date: 2020-09-11 17:47
 */
@Component
public class FileListener extends FileAlterationListenerAdaptor {

    private Logger log = LoggerFactory.getLogger(FileListener.class);

    private static Map<String, Long> fileSeekIndex = new ConcurrentHashMap<>();

    private NettyClient client;

    private String source;

    public FileListener(String source, NettyClient nettyClient) {
        this.source = source;
        this.client = nettyClient;
    }

    public FileListener() {
    }

    /**
     * 文件创建执行
     */
    public void onFileCreate(File file) {
        log.debug("[文件创建执行]:" + file.getAbsolutePath());
        fileSeekIndex.put(file.getName(), 0L);
    }

    /**
     * 文件创建修改
     */
    public void onFileChange(File file) {
        long index;
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
            if (!fileSeekIndex.containsKey(file.getName())) {
                index = raf.length();
                fileSeekIndex.put(file.getName(), index);
            } else {
                index = fileSeekIndex.get(file.getName());
            }
            raf.seek(index);

            String line = null;
            while ((line = raf.readLine()) != null) {
                String content = new String(line.getBytes("ISO-8859-1"), "utf-8");
                if (!StringUtils.isEmpty(content)) {
                    send(content, file.getName());
                }
            }
            fileSeekIndex.put(file.getName(), raf.getFilePointer());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件删除
     */
    public void onFileDelete(File file) {
        log.debug("[文件删除]:" + file.getAbsolutePath());
        fileSeekIndex.remove(file.getName());
    }

    /**
     * 目录创建
     */
    public void onDirectoryCreate(File directory) {
        log.info("[目录创建]:" + directory.getAbsolutePath());
    }

    /**
     * 目录修改
     */
    public void onDirectoryChange(File directory) {
        log.info("[目录修改]:" + directory.getAbsolutePath());
    }

    /**
     * 目录删除
     */
    public void onDirectoryDelete(File directory) {
        log.info("[目录删除]:" + directory.getAbsolutePath());
    }

    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
    }

    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
    }

    /**
     * 发送日志消息
     *
     * @param content
     * @param fileName
     */
    public void send(String content, String fileName) {
        WebLogMeta meta = new WebLogMeta();
        meta.setContent(content);
        meta.setFileName(fileName);
        meta.setSource(this.source);
        try {
            client.remoteCall(meta, 1);
        } catch (Exception e) {
            if (e instanceof ConnectException) {
                log.error("连接服务端失败! e:{}", e.getMessage());
            } else {
                log.error("发送日志到服务端失败! e:{}", e.getMessage());
            }
        }

    }

}
